<template>
    <div class="com-container">
        <!-- <button @click="test">test</button> -->
        <div class="com-chart" ref="hot_ref"></div>
        <span class="iconfont arr-left" @click="toLeft" :style="comStyle"
            >&#xe6ef;</span
        >
        <span class="iconfont arr-right" @click="toRight" :style="comStyle"
            >&#xe6ed;</span
        >
        <span class="cat-name" :style="comStyle">{{ catName }}</span>
    </div>
</template>

<script setup>
import {
    ref,
    onMounted,
    onUnmounted,
    inject,
    computed,
    defineExpose,
    watch,
    nextTick,
} from "vue";
import * as echarts from "echarts";
import SocketService from "./../utils/socket_service";
//vuex
import { useStore } from "vuex";
const store = useStore();
import { getThemeValue } from "@/utils/theme_utils";

let allData = ref(null);
let chartInstance = null;
const hot_ref = ref(null);
console.log(hot_ref);
let currentIndex = ref(0); //一级分类数据
let titleFontSize = ref(null);

const toLeft = () => {
    currentIndex.value--;
    if (currentIndex.value < 0) {
        currentIndex.value = allData.value.length - 1;
    }
    upDataChart();
};
const toRight = () => {
    currentIndex.value++;
    if (currentIndex.value > allData.value.length - 1) {
        currentIndex.value = 0;
    }
    upDataChart();
};
const catName = computed(() => {
    if (!allData.value) {
        return "";
    } else {
        return allData.value[currentIndex.value].name;
    }
});
const comStyle = computed(() => {
    return {
        fontSize: `${titleFontSize.value}px`,
        color: getThemeValue(theme.value).titleColor,
    };
});
//初始化
const initChart = () => {
    console.log("注册组件");
    //挂载chart
    chartInstance = echarts.init(hot_ref.value, theme.value);
    /** @type EChartsOption */
    const initOption = {
        title: {
            text: "| 热销商品",
            left: 20,
            top: 20,
        },
        legend: {
            top: "15%",
            icon: "circle",
        },
        tooltip: {
            show: true,
            formatter: (arg) => {
                //提示框类容
                // console.log(arg);
                const thirdCategory = arg.data.children;
                let total = 0;
                thirdCategory.forEach((item) => {
                    total += item.value;
                });
                // console.log(total);
                // console.log(thirdCategory);
                let retStr = "";
                thirdCategory.forEach((item) => {
                    // console.log((item.value / total) * 100);
                    retStr += `
                        ${item.name}:${parseInt((item.value / total) * 100)}%
                        </br>
                    `;
                });
                return retStr;
            },
        },
        series: [
            {
                type: "pie",
                label: {
                    show: false,
                },
                emphasis: {
                    //高亮状态下的样式
                    label: {
                        show: true,
                    },
                    labelLine: {
                        show: false,
                    },
                },
            },
        ],
    };
    chartInstance.setOption(initOption);
};
//更新
const getData = async (ret) => {
    // 获取数据
    // const { data: ret } = await inject("http").get("/api/hot");
    allData.value = ret;
    console.log(allData.value);
    upDataChart();
};
//获取数据
const upDataChart = () => {
    //处理数据
    const legendData = allData.value[currentIndex.value].children.map(
        (item) => {
            return item.name;
        }
    );
    const seriesData = allData.value[currentIndex.value].children.map(
        (item) => {
            return {
                name: item.name,
                value: item.value,
                children: item.children,
            };
        }
    );
    /** @type EChartsOption */
    const dataOption = {
        legend: {
            data: legendData,
        },
        series: [
            {
                data: seriesData,
            },
        ],
    };
    chartInstance.setOption(dataOption);
};
// 响应式适配
const screenAdapt = () => {
    console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    //标题文字
    titleFontSize.value = hot_ref.value.offsetWidth * (66 / 1536);
    console.log(titleFontSize.value);
    /** @type EChartsOption */
    const adaptOption = {
        title: {
            textStyle: {
                fontSize: titleFontSize.value,
            },
        },
        series: [
            {
                radius: titleFontSize.value * 4.5,
                center: ["50%", "60%"],
            },
        ],
        legend: {
            itemWidth: titleFontSize.value,
            itemHeight: titleFontSize.value,
            itemGap: titleFontSize.value / 2, //图例间隔
            textStyle: {
                fontSize: titleFontSize.value / 2,
            },
        },
    };
    chartInstance.setOption(adaptOption);
    chartInstance.resize();
};
// const test = () => {
//     store.commit("changeTheme");
//     console.log("主题切换了");
//     chartInstance.dispose(); //销毁当前图表
//     initChart();
//     toLeft();
//     toRight();
//     screenAdapt();
//     // console.log(theme.value);
// };
// 回调函数注册
inject("SocketService").registerCallBack("hotData", getData);
onUnmounted(() => {
    inject("SocketService"), unRegisterCallBack("hotData");
});

onMounted(() => {
    initChart();
    // getData();
    inject("SocketService").send({
        action: "getData",
        socketType: "hotData",
        chartName: "hot",
        value: "",
    });
    window.addEventListener("resize", screenAdapt);
    screenAdapt();
    console.log("##############", hot_ref.value);
});
onUnmounted(() => {
    window.removeEventListener("resize", screenAdapt);
});

//更换主题
const theme = computed(() => {
    return store.state.theme;
});
watch(theme, () => {
    console.log("主题切换了");
    chartInstance.dispose(); //销毁当前图表
    initChart();
    SocketService.Instance.send({
        action: "getData",
        socketType: "hotData",
        chartName: "hot",
        value: "",
    });
    screenAdapt();
    // console.log(theme.value);
});

defineExpose({
    screenAdapt,
});
</script>

<style lang="scss" scoped>
.arr-left {
    position: absolute;
    left: 10%;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    color: #fff;
}
.arr-right {
    position: absolute;
    right: 10%;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    color: #fff;
}
.cat-name {
    position: absolute;
    left: 80%;
    bottom: 10%;
    color: #fff;
}
</style>